<template>
  <template v-if="!showChart">
    <div class="text-[16px] text-left">该组件无统计图表</div>
  </template>
  <template v-else>
    <div id="chartDom" style="width: 100%; height: 500px"></div>
  </template>
</template>
<script setup>
import * as echarts from 'echarts'
import {nextTick, ref, watch,onBeforeUnmount} from "vue";
import useQuestion from "../../store/question.js";
import {storeToRefs} from "pinia";
onBeforeUnmount(()=>{
  myChart.value?.dispose();
})
let myChart = ref(null)
let showChart = ref(false)
const {chartsViewOptions, activeData} = storeToRefs(useQuestion())
watch(() => activeData.value, (newVal) => {
  myChart.value?.dispose();
  if (newVal?.type === 'questionRadio') {
    initPie()
    showChart.value = true
  } else if (newVal?.type === 'questionCheckbox') {
    initBar()
    showChart.value = true
  } else {
    showChart.value = false
  }
}, {immediate: true})
const initPie = () => {
  let data = []
  chartsViewOptions.value.forEach((i) => {
    data.push({
      name: i.text,
      value: Math.floor(Math.random() * (100 - 10) + 10)
    })
  })
  nextTick(() => {
    let chartDom = document.getElementById('chartDom')
    myChart.value = echarts.init(chartDom);
    let option;
    option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    option && myChart.value.setOption(option);
  })
}
const initBar = () => {
  let data = []
  let value = []
  chartsViewOptions.value.forEach((i) => {
    data.push (i.text)
    value.push(Math.floor(Math.random() * (100 - 10) + 10))
  })
  nextTick(() => {
    let chartDom = document.getElementById('chartDom')
    myChart.value = echarts.init(chartDom);
    let option;
    option = {
      tooltip: {
        trigger: 'item'
      },
      xAxis: {
        type: 'category',
        data: data
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: value,
          type: 'bar'
        }
      ]
    };
    option && myChart.value.setOption(option);
  })
}
</script>
